<?php namespace App\Controllers;

use \App\App;

class Search extends App
{
    private $searchModel;
    public function __construct()
    {
        parent::__construct();
        $this->language->load('app/user');
        $this->searchModel = new \App\Models\Search();
    }

    public function index()
    {
        $key = $this->request->request("key");
        $type = $this->request->request('type') ?: "local";
        $page = $this->request->request("page") ?: 0;
        if ($key) {
            if ($type == "cloud") {
                $story = $this->cloud($key, $page);
            } else {
                $story = $this->local($key, $page);
            }
            $search = $this->searchModel->where("title", $key)->first();
            if ($search) {
                $search['count']++;
            } else {
                $search = ["title" => $key, "count" => 1];
            }
            $this->searchModel->save($search);
            $this->view->stories = $story;
            $this->view->viewTitle = "搜索 " . $key;
            $this->view->key = $key;
            $this->view->type = $type;
            $this->view->page = $page;
            if ($this->request->isAJAX()) {
                $this->render("front/search/list", "front/header");
            }
        }
        $this->view->searchKeys = $this->searchModel->order("count", "DESC")->findAll(10);

        $this->render("front/search/search", "front/header");
    }

    public function local($key, $page)
    {
        $storyModel = new \App\Models\Story();

        $story['books'] = $storyModel->where('title', $key, "like")
            ->where("author", $key, "like", true)
            ->findAll(20, $page * 20);
        $story['total'] = $storyModel->count();
        return $story;
    }

    public function cloud($key, $page)
    {
        $api = new \App\Models\Api(1);
        $story = $api->getUrl("search", ['query' => $key, "limit" => 20, "start" => $page * 20]);
        $this->view->staticUrl = $api->getUrl("static", "", false);
        return $story;
    }

    public function key()
    {
        $query = $this->request->get('q');
        if($query) {
            $this->searchModel->where("title", $query, "like");
        }
        $result['items'] = $this->searchModel->order("count","DESC")->findAll(7);
        $this->showJson($result);
    }
}